package com.liu.qqRobot.poke.handler;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.common.content.RedisKeyInterface;
import com.liu.common.utils.HtmlToImageUtils;
import com.liu.common.utils.QQClientUtils;
import com.liu.mybatisPlus.poke.entity.base.PokeDuel;
import com.liu.mybatisPlus.poke.entity.base.PokeDuelDetail;
import com.liu.mybatisPlus.poke.service.PokeDuelDetailService;
import com.liu.mybatisPlus.poke.service.PokeDuelService;
import com.liu.mybatisPlus.poke.service.PokeGroupUserPokeService;
import com.liu.mybatisPlus.q.entity.base.QGroupUser;
import com.liu.mybatisPlus.q.service.QGroupUserOperationQuantityService;
import com.liu.mybatisPlus.q.service.QGroupUserService;
import com.liu.qqRobot.event.entity.dto.EventReportingDTO;
import com.liu.qqRobot.poke.entity.dto.PokeDTO;
import com.liu.qqRobot.q.enums.OperationTypeEnum;
import freemarker.template.TemplateException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class ComeOutPokeHandler {

    @Resource
    private PokeGroupUserPokeService pokeGroupUserPokeService;

    @Resource
    private QGroupUserOperationQuantityService qGroupUserOperationQuantityService;

    @Resource
    private PokeDuelService pokeDuelService;

    @Resource
    private PokeDuelDetailService pokeDuelDetailService;

    @Resource
    private QGroupUserService qGroupUserService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 处理事件
     * @param data 信息内容
     * @param groupId 群号
     * @param userId 发送人QQ号
     */
    @Transactional
    public void handler(EventReportingDTO.Message.Data data, Long groupId, Long userId, Boolean isGroup) {
        String text = data.getText();
        String pokeName = text.replace("出来吧 ", "");
        PokeDTO pokeDTO = pokeGroupUserPokeService.getPokeByUserIdAndPokeName(groupId, userId, pokeName);
        if (pokeDTO == null) {
            return;
        }
        QueryWrapper<PokeDuel> pokeDuelQueryWrapper = new QueryWrapper<>();
        pokeDuelQueryWrapper.eq("group_id", groupId);
        pokeDuelQueryWrapper.eq("is_end", 0);
        PokeDuel groupPokeDuel = pokeDuelService.getOne(pokeDuelQueryWrapper);
        pokeDuelQueryWrapper.and(pokeDuelQueryWrapper1 -> pokeDuelQueryWrapper1.eq("user1_id", userId).or().eq("user2_id", userId));
        PokeDuel userPokeDuel = pokeDuelService.getOne(pokeDuelQueryWrapper);
        if (userPokeDuel != null) {
            return;
        }
        QueryWrapper<QGroupUser> qGroupUserQueryWrapper = new QueryWrapper<>();
        qGroupUserQueryWrapper.eq("group_id", groupId);
        qGroupUserQueryWrapper.eq("user_id", userId);
        QGroupUser qGroupUser = qGroupUserService.getOne(qGroupUserQueryWrapper);
        int isCreate = 1;
        String user1Name = null;
        if (groupPokeDuel == null) {
            // 创建对决
            groupPokeDuel = new PokeDuel();
            groupPokeDuel.setGroup1Id(groupId);
            groupPokeDuel.setUser1Id(userId);
            groupPokeDuel.setUser1PokeId(pokeDTO.getPokeId());
            pokeDuelService.save(groupPokeDuel);
            redisTemplate.opsForValue().set(RedisKeyInterface.POKE_HP_REDIS_KEY + groupPokeDuel.getId() + userId, String.valueOf(pokeDTO.getHp()));
            // 创建对决详情
            PokeDuelDetail pokeDuelDetail = new PokeDuelDetail();
            pokeDuelDetail.setDuelId(groupPokeDuel.getId());
            pokeDuelDetail.setUserId(userId);
            String content = "【" + (qGroupUser.getGroupUserName() == null ? qGroupUser.getUserName():qGroupUser.getGroupUserName()) + "】创建对决";
            pokeDuelDetail.setContent(content);
            pokeDuelDetail.setSort(0);
            pokeDuelDetailService.save(pokeDuelDetail);
        } else {
            // 加入对决
            groupPokeDuel.setUser2Id(userId);
            groupPokeDuel.setUser2PokeId(pokeDTO.getPokeId());
            groupPokeDuel.setNextUseUserId(groupPokeDuel.getUser1Id());
            pokeDuelService.updateById(groupPokeDuel);
            redisTemplate.opsForValue().set(RedisKeyInterface.POKE_HP_REDIS_KEY + groupPokeDuel.getId() + userId, String.valueOf(pokeDTO.getHp()));
            // 创建对决详情
            PokeDuelDetail pokeDuelDetail = new PokeDuelDetail();
            pokeDuelDetail.setDuelId(groupPokeDuel.getId());
            pokeDuelDetail.setUserId(userId);
            String content = "【" + (qGroupUser.getGroupUserName() == null ? qGroupUser.getUserName():qGroupUser.getGroupUserName()) + "】加入对决";
            pokeDuelDetail.setContent(content);
            pokeDuelDetail.setSort(1);
            pokeDuelDetailService.save(pokeDuelDetail);
            QueryWrapper<QGroupUser> qGroupUser1QueryWrapper = new QueryWrapper<>();
            qGroupUser1QueryWrapper.eq("group_id", groupId);
            qGroupUser1QueryWrapper.eq("user_id", groupPokeDuel.getUser1Id());
            QGroupUser qGroupUser1 = qGroupUserService.getOne(qGroupUser1QueryWrapper);
            user1Name = qGroupUser1.getGroupUserName();
            isCreate = 0;
        }

        Map<String, Object> templateParam = new HashMap<>();
        templateParam.put("pokeName", pokeDTO.getPokeName());
        templateParam.put("pokeImageUrl", pokeDTO.getPokeImageUrl());
        templateParam.put("isCreate", isCreate);
        templateParam.put("user1Name", user1Name);
        try {
            HtmlToImageUtils.htmlToImage("comeOutPokeTemplate.html", templateParam, "src/main/resources/picture/comeOutPoke.png", 1100);
            File file = new File("src/main/resources/picture/comeOutPoke.png");
            String encode = Base64.encode(file);
            String msg = "[CQ:at,qq=" + userId + "]\n[CQ:image,file=base64://" + encode+ ",type=show,subType=0]";
            QQClientUtils.sendMsg(msg, userId, groupId, isGroup);
            qGroupUserOperationQuantityService.statisticsOperationQuantityByType(groupId, userId, OperationTypeEnum.COME_OUT_POKE);
        } catch (IOException | ParserConfigurationException | SAXException | TemplateException e) {
            log.error("获取出来吧宝可梦展示模板失败:{}", e.getMessage(), e);
//            QQClientUtils.sendGroupMsg("[CQ:at,qq=" + userId + "]\n获取捕捉宝可梦展示模板失败，请联系制作人", userId, groupId, isGroup);
        }
        if (isCreate == 0) {
            QQClientUtils.sendMsg("[CQ:at,qq=" + groupPokeDuel.getUser1Id() + "]\n请开始行动，发送指令：使用 XXX", groupPokeDuel.getUser1Id(), groupId, isGroup);
        }
    }

}
